/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package recommender.dbi;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;
import recommender.objects.Entity;
import recommender.objects.Parent;

/**
 *
 * @author Aya
 */
public class KBI extends DBI{

    private final EntityManager em;
    
    public KBI(){
        EntityManagerFactory factory = Persistence.createEntityManagerFactory("RecommenderPU");
        em = factory.createEntityManager();   
    }
    
    @Override
    public List<Entity> getTopLevelNodes() {
        Query q = em.createNativeQuery("SELECT * FROM kb.get_top_level_classes()", Entity.class);
        return q.getResultList();
    }

    @Override
    public List<Entity> getAllEntities() {
        Query q = em.createNativeQuery("SELECT * FROM kb.get_all_entities()", Entity.class);
        return q.getResultList();
    }

    @Override
    public List<Parent> getParentsOf(Entity e) {
        Query q = em.createNativeQuery("SELECT * FROM kb.get_parents(?1, ?2)", Parent.class);
        q.setParameter(1, e.isClass());
        q.setParameter(2, e.getId());
        return q.getResultList();
    }

    @Override
    public Entity getEntity(String identifier) throws Exception{
        Query q = em.createNativeQuery("SELECT * FROM kb.get_entity(?1, ?2)", Entity.class);
        q.setParameter(1, identifier.startsWith("Class"));
        int id = Integer.parseInt(identifier.replace("Class", "").replace("Instance", ""));
        q.setParameter(2, id);
        List<Entity> e = q.getResultList();
        if(e != null && !e.isEmpty())
            return e.get(0);
        else
            throw new Exception("Entity not found");
    }
    
    public List<Entity> getEntitiesOfVideosTill(int n){
        Query q = em.createNativeQuery("SELECT * FROM kb.get_entities_till(?1)", Entity.class);
        q.setParameter(1, n);
        return q.getResultList();
    }
}
